package com.yami.shop.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.cashregisterapp.AppShopCashResult;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.SimpleCaptcha;
import com.yami.shop.dao.CashOutMapper;
import com.yami.shop.dao.AppShopCashResultMapper;
import com.yami.shop.service.CashOutService;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.service.UserService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.yami.shop.common.bean.SuperDto;
import com.yami.shop.common.util.SuperUtil;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
@Transactional(rollbackFor = Exception.class)
public class CashOutServiceImpl extends ServiceImpl<CashOutMapper, CashOut> implements CashOutService {
    @Autowired
    private CashOutService cashOutService;

    @Autowired
    private CashOutMapper cashOutMapper;

    @Autowired
    private AppShopCashResultMapper appShopCashResultMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private ShopDetailService shopDetailService;

    /**
     * 提现审核修改状态
     * @param
     */
    @Override
    public void updateAndCash(CashOut cashOut) {
        int state = cashOut.getState();
        if(state == 1){

        }
        cashOutService.updateById(cashOut);
    }

    @Override
    public String getAllIncome(String userId) {
        return cashOutMapper.getAllIncome(userId);
    }

    @Override
    public String getMoneyByCode(String userId, String puserID) {
        return cashOutMapper.getMoneyByCode(userId,puserID);
    }

    @Override
    public List<PromoTionOrder> getPromoTionOrder(String userId) {
        return cashOutMapper.getPromoTionOrder(userId);
    }

    @Override
    public List<OrderItem> getOrderItem(String orderNumber) {
        return cashOutMapper.getOrderItem(orderNumber);
    }

    @Override
    public List<PromoTionOrder> getdjsOrder(String userId) {
        return cashOutMapper.getdjsOrder(userId);
    }

    @Override
    public List<PromoTionOrder> getyjsOrder(String userId) {
        return cashOutMapper.getyjsOrder(userId);
    }

    @Override
    public List<RebateRecords> getIncomeDetails(String userId) {
        return cashOutMapper.getIncomeDetails(userId);
    }

    @Override
    public List<PromotionGoods> getPromotionGoods(String shopId) {
        return cashOutMapper.getPromotionGoods(shopId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public  CashOut appCashOut(Double cashOutMoney,String remark,Long shopId,Long userId){
        CashOut cashOut = new CashOut();
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
        cashOut.setShopId(shopId);
        cashOut.setState(2);
        cashOut.setUserId(userId.toString());
        cashOut.setRemark(remark);
        cashOut.setBankAccount(shopDetail.getCardNumber());
        cashOut.setCreateTime(new Date());
        cashOut.setCashOutMoney(cashOutMoney);
        cashOut.setUserType( new Character('1'));//1:商家，2:用户
        cashOut.setBankAccount(shopDetail.getCardNumber());
        cashOut.setBankName(shopDetail.getOpenBank());
        cashOut.setCreateTime(new Date());
        cashOut.setShopName(shopDetail.getShopName());
        cashOutService.save(cashOut);
        //获取用户的账户余额
        Double currentMoney =  shopDetail.getCashMoney();
        //扣除账户提现的金额
        Double remainMoney =  Arith.sub(currentMoney,Double.valueOf(cashOutMoney));
        shopDetail.setCashMoney(remainMoney);
        shopDetailService.updateById(shopDetail);
        return cashOut;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dealCashOut(String name, String bankAccount, String amount,String userId,String bankName) {
        //申请提现的时候,先用提现金额和申请金额做比较,当金额符合要求的时候,扣除账户金额
        User user = userService.getUserByUserId(userId);
        //获取用户的账户余额
        Double currentMoney =  user.getAccount();
        if(Double.valueOf(amount)>currentMoney){
            return;
        }
        //扣除账户提现的金额
        Double remainMoney =  Arith.sub(currentMoney,Double.valueOf(amount));
        user.setAccount(remainMoney);
        userService.updateById(user);
        //生成提现记录
        CashOut cashOut = new CashOut();
        cashOut.setState(2);
        cashOut.setName(name);
        cashOut.setUserType('2');
        cashOut.setBankAccount(bankAccount);
        cashOut.setCashOutMoney(Double.valueOf(amount));
        cashOut.setCreateTime(new Date());
        cashOut.setUserId(userId);
        cashOut.setNickName(user.getNickName());
        cashOut.setBankName(bankName);
        cashOutService.save(cashOut);
    }

    @Override
    public List<CashOut> getWithdrawalRecord(String userId) {
        return cashOutMapper.getWithdrawalRecord(userId);
    }

    @Override
    public List<CashOut> getytgWithdrawalRecord(String userId) {
        return cashOutMapper.getytgWithdrawalRecord(userId);
    }

    @Override
    public List<CashOut> getdshWithdrawalRecord(String userId) {
        return cashOutMapper.getdshWithdrawalRecord(userId);
    }

    @Override
    public List<PromotionGoods> getRecentGoods(String shopId) {
        return cashOutMapper.getRecentGoods(shopId);
    }

    @Override
    public List<PromotionGoods> getSellWellGoods(String shopId) {
        return cashOutMapper.getSellWellGoods(shopId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cashOutByShop(Long shopId, String cashOUtMoney) {
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
        //申请提现后减去提现的金额,申请提现金额必须要小于等于可提现金额
        //可提现金额
        BigDecimal decimal = new BigDecimal(shopDetail.getCashMoney()).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal decimal1 = new BigDecimal(cashOUtMoney);
        if(decimal.compareTo(decimal1)>-1) {
            Double remainMoney = Arith.sub(shopDetail.getCashMoney(), Double.valueOf(cashOUtMoney));
            shopDetail.setCashMoney(remainMoney);
            shopDetailService.saveOrUpdate(shopDetail);
            //申请人姓名
            String name = shopDetail.getCardOwner();
            //申请人卡号
            String cardNumber = shopDetail.getCardNumber();
            //创建申请记录
            CashOut cashOut = new CashOut();
            cashOut.setUserType('1');
            cashOut.setState(2);
            cashOut.setCreateTime(new Date());
            cashOut.setCashOutMoney(Double.valueOf(cashOUtMoney));
            cashOut.setShopId(shopId);
            cashOut.setName(name);
            cashOut.setBankAccount(cardNumber);
            cashOut.setShopName(shopDetail.getShopName());
            cashOutService.save(cashOut);
        }
    }

    @Override
    public List<CashOut> cashOutItems(Integer state, DateTime lessThanUpdateTime) {
        return cashOutMapper.cashOutItems(state,lessThanUpdateTime);
    }

    //申请提现分账驳回
    @Override
    @Transactional
    public CashOut cashOutReject(Long cashId,int status,String reason){
        //驳回，申请提现金额返回原账户
        CashOut cashOut = cashOutMapper.selectById(cashId);
        cashOut.setState(status);
        cashOut.setApprovalTime(new Date());
        cashOut.setReason(reason);
        cashOutMapper.updateById(cashOut);
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(cashOut.getShopId());
        shopDetail.setCashMoney(cashOut.getCashOutMoney()+shopDetail.getCashMoney());
        shopDetailService.saveOrUpdate(shopDetail);
        return cashOut;
    }

    /**
     * 店铺账户查询接口
     * */
    @Override
    public String shopAccount(){
        SuperDto superDto = new SuperDto();
        superDto.setTransCode("202006");//交易码  商户信息查询交易码
        superDto.setMerNo("zg000000047866");//企业用户号
        String result = SuperUtil.oneStep(superDto);
        return result;
    }


    //商户查询银联账户接口
    @Override
    public String  umsShopAccount(Long shopId,String merNo){
        SuperDto superDto = new SuperDto();
        superDto.setTransCode("202011");
        //superDto.setReqDate("20200319"); //请求日期
        //superDto.setSrcReqTime("203200");
        superDto.setMerNo(merNo);//企业用户号
        superDto.setAcctType("2");
        String result = SuperUtil.oneStep(superDto);
        return result;
    }

    //平台分账
    @Override
    public Boolean separateAccount(){
        SuperDto superDto = new SuperDto();
        superDto.setTransCode("202004");
        superDto.setMerNo("zg000000047866");
        superDto.setPayType("0");
        superDto.setCardNo("6214852117312549");//
        superDto.setPayAmt("360");
        superDto.setPs("平台提现");//附言
        String result = SuperUtil.oneStep(superDto);
        JSONObject json = new JSONObject(result);
        String respCode = json.getString("respCode");
        if (respCode.equals("99999999")) {
            return true;
        }else{
            return false;
        }
    }

    //划付
    @Override
    public Boolean cashOutReview(Long cashId,int status,String reason,String bankAccount) {
        CashOut cashOut = cashOutService.getById(cashId);
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(cashOut.getShopId());
        SuperDto superDto = new SuperDto();
        superDto.setTransCode("202002"); //按金额划付交易码
        superDto.setMerNo("zg000000052155");//企业用户号
        superDto.setPayType("0"); //分账类型 0-指定金额分账（目前只支持0）
        //superDto.setPayAmt(cashOut.getCashOutMoney().toString()); //分账金额
        BigDecimal cashMoney = new BigDecimal(cashOut.getCashOutMoney()).setScale(2,BigDecimal.ROUND_HALF_UP);
        BigDecimal c = new BigDecimal("100");
        BigDecimal result1 = cashMoney.multiply(c).setScale(0,BigDecimal.ROUND_HALF_UP);
        superDto.setPayAmt(String.valueOf(result1)); //分账金额
        System.out.println("提现金额"+String.valueOf(result1));
        //superDto.setCardNo(bankAccount);//卡号
        superDto.setPs(shopDetail.getShopName() + "店铺");//附言
        String result = SuperUtil.oneStep(superDto);
        System.out.println("提现银联返回结果 "+result);
        JSONObject json = new JSONObject(result);
        String respCode = json.getString("respCode");
        if (respCode.equals("99999999")) {
            //提现成功，减去账户可提现金额
            // status 提现状态(0:审核通过1:审核失败2:待审核)
            cashOut.setState(0);
            cashOut.setApprovalTime(new Date());
            cashOut.setReason(reason);
            cashOutService.saveOrUpdate(cashOut);
           /* Double cashOutMoney = cashOut.getCashOutMoney();
            shopDetail.setCashMoney(shopDetail.getCashMoney() + cashOutMoney);
            shopDetailService.saveOrUpdate(shopDetail);*/
            //成功
            AppShopCashResult appShopCashResult = new AppShopCashResult();
            appShopCashResult.setIsSuccess(1);
            appShopCashResult.setTransCode("202004");
            appShopCashResult.setSrcReqDate(new Date());
            appShopCashResult.setCashId(cashOut.getCashId());
            appShopCashResult.setSrcReqId(json.getString("srcReqId"));//流水号
            appShopCashResult.setChannelId("");//渠道号
            appShopCashResult.setGroupId("HBXELD");//集团号
            appShopCashResult.setReqSignatrue("");//请求签名
            appShopCashResult.setRespCode("99999999");//请求结果
            appShopCashResult.setShopId(cashOut.getShopId());
            appShopCashResult.setBankAccount(bankAccount);
            //appShopCashResult.setRespSignature(json.getString("respSignature"));//返回签名
            appShopCashResultMapper.insert(appShopCashResult);
            return true;
        } else {
            //失败
            String respMsg = json.getString("respMsg");
            AppShopCashResult appShopCashResult = new AppShopCashResult();
            appShopCashResult.setTransCode("202004");
            appShopCashResult.setSrcReqDate(new Date());
            appShopCashResult.setCashId(cashOut.getCashId());
            appShopCashResult.setSrcReqId(json.getString("srcReqId"));//流水号
            appShopCashResult.setChannelId("");//渠道号
            appShopCashResult.setGroupId("HBXELD");//集团号
            appShopCashResult.setReqSignatrue("");//请求签名
            appShopCashResult.setRespCode(json.getString("respCode"));//请求返回码
            //appShopCashResult.setRespSignature(json.getString("respSignature"));//返回签名
            appShopCashResult.setRespMsg(respMsg);
            appShopCashResult.setShopId(cashOut.getShopId());
            appShopCashResult.setBankAccount(bankAccount);
            appShopCashResult.setIsSuccess(0);//失败
            appShopCashResultMapper.insert(appShopCashResult);
            return false;
        }
    }

}
